<template>
	<div class="container">
		<Breadcrumb :items="['menu.card', 'menu.card.index']" />
		<a-card :title="$t('menu.card.index')">
			<a-space fill direction="vertical">
				<a-row :gutter="16">
					<a-col :span="3">
						<a-select
								v-model="searchParams.company_id"
								placeholder="选择公司"
								:loading="companyLoading"
								allow-clear
								style="width:100%;"
							>
								<a-option v-for="company in companyOptions" :key="company.id" :value="company.id">
									{{ company.name }}
								</a-option>
							</a-select>
					</a-col>
					<a-col :span="4">
						<a-range-picker
							v-model="searchParams.dateRange"
							:placeholder="['开始时间', '结束时间']"
							style="width: 100%;"
						/>
					</a-col>
					<a-col :span="6">
						<a-space>
							<a-button type="primary" @click="onSearch">
								<template #icon><icon-search /></template>
								搜索
							</a-button>
							<a-button @click="resetSearch">
								<template #icon><icon-refresh /></template>
								重置
							</a-button>
						</a-space>
					</a-col>
				</a-row>
				<a-row :gutter="16">
					<a-col :span="12">
						<a-space fill>
							<a-button type="primary" @click="openModal()" shape="round">
								<template #icon><icon-plus /></template>
								添加福利卡
							</a-button>
							<a-button type="outline" @click="openBindRecordsDrawer()" shape="round">
								<template #icon><icon-user /></template>
								绑定记录
							</a-button>
						</a-space>
					</a-col>
					<a-col :flex="1">
						
					</a-col>
				</a-row>

				<a-table :data="renderData" :loading="loading" :bordered="{ cell: true }" :pagination="pagination"
					@page-change="onPageChange" @page-size-change="onPageSizeChange" :scroll="{ x: '2000' }">
					<template #columns>
						<a-table-column title="ID" data-index="id" :width="80" />
						<a-table-column title="图片" data-index="image" :width="80">
							<template #cell="{ record }">
								<a-image :src="record.image_url" width="40" height="40" />
							</template>
						</a-table-column>
						<a-table-column title="发放公司" data-index="company_name" :width="150" />
						<a-table-column title="名称" data-index="name" :width="150" />
						<a-table-column title="面值" data-index="score" :width="120" />
						<a-table-column title="默认过期天数" data-index="expired_days" :width="120">
							<template #cell="{ record }">
								{{ record.expired_days }}天
							</template>
						</a-table-column>
						<a-table-column title="总额度" data-index="expired_days" :width="120">
							<template #cell="{ record }">
								{{ record.score*record.item_total }}
							</template>
						</a-table-column>
						<a-table-column title="卡价格" data-index="price" :width="120">
							<template #cell="{ record }">
								{{ record.type == 'topic' ? record.price : '-' }}
							</template>
						</a-table-column>
						<a-table-column title="卡数量" data-index="total" :width="120">
							<template #cell="{ record }">
								{{ record.type == 'topic' ? record.total : '-' }}
							</template>
						</a-table-column>
						<a-table-column title="已绑定卡片数" data-index="user_total" :width="120">
							<template #cell="{ record }">
								{{ record.user_total }}
							</template>
						</a-table-column>
						<a-table-column title="使用额度" data-index="user_total_score" :width="120"/>
						<a-table-column title="剩余额度" :width="120">
							<template #cell="{ record }">
								{{ record.score*record.item_total - record.user_total_score }}
							</template>
						</a-table-column>
						<a-table-column title="卡片数" data-index="item_total" :width="120">
							<template #cell="{ record }">
								<a-link @click="openCardItemList(record)">
									{{ record.item_total}}
								</a-link>
							</template>
						</a-table-column>
						<a-table-column title="创建时间" data-index="created_at" :width="180" />
						<a-table-column title="排序" data-index="sort_by" :width="100" />
						<a-table-column title="操作" align="center" :width="180" fixed="right">
							<template #cell="{ record }">
								<a-space size="mini">
									<a-link @click="openModal(record)">
										编辑
									</a-link>
									<a-link @click="openGenerateModal(record)" v-if="record.type == 'company'">
										生成卡片
									</a-link>
									<a-popconfirm position="left" content="确定要删除这个福利卡吗？" @ok="handleDelete(record.id)">
										<a-link>
											删除
										</a-link>
									</a-popconfirm>
								</a-space>
							</template>
						</a-table-column>
					</template>
				</a-table>
			</a-space>
		</a-card>

		<a-modal v-model:visible="modalVisible" width="750px" :draggable="true" :title="formData.id ? '编辑福利卡' : '添加福利卡'"
			@before-ok="handleSubmit" @cancel="closeModal">
			<a-form :model="formData" ref="formRef" layout="vertical">
				<a-row :gutter="16">
					<a-col :span="12">
						<a-form-item field="name" label="名称" :rules="[{ required: true }]">
							<a-input v-model="formData.name" placeholder="请输入名称" />
						</a-form-item>
					</a-col>
					<a-col :span="12">
						<a-form-item field="score" label="云豆数" :rules="[{ required: true }]">
							<a-input-number v-model="formData.score" placeholder="请输入云豆数" :min="0" />
						</a-form-item>
					</a-col>
					<a-col :span="12">
						<a-form-item field="sort_by" label="排序" :rules="[{ required: true }]">
							<a-input-number v-model="formData.sort_by" placeholder="请输入排序" />
						</a-form-item>
					</a-col>
					<a-col :span="12">
						<a-form-item field="expired_days" label="默认过期时间(天)">
							<a-input-number v-model="formData.expired_days" placeholder="请输入过期时间，0表示永久有效" :min="0" />
						</a-form-item>
					</a-col>
				</a-row>
					<a-form-item label="图片" :rules="[{ required: true }]">
						<a-upload list-type="picture" v-model="formData.image" :custom-request="handleUpload" :limit="1"
							:file-list="fileList" image-preview @before-remove="beforeRemove" />
						<template #extra>
							<div>请保持图片比例为1.59:1（全球统一的通用规格），格式为jpg/png</div>
						</template>
					</a-form-item>
				
				<a-row :gutter="16">	
					
					<a-col :span="12">
						<a-form-item field="type" label="类型" :rules="[{ required: true }]">
							<a-select
								v-model="formData.type"
								placeholder="请选择类型"
							>
								<a-option  value="company">单位富利卡</a-option>
								<a-option  value="topic">平台主题卡</a-option>
							</a-select>
						</a-form-item>
					</a-col>
					<template v-if="formData.type === 'topic'">
						<a-col :span="12">
							<a-form-item field="price" label="卡价格">
								<a-input-number v-model="formData.price" placeholder="请输入卡价格" :min="0" />
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item field="total" label="卡数量">
								<a-input-number v-model="formData.total" placeholder="请输入卡数量" :min="0" />
							</a-form-item>
						</a-col>
					</template>
					
					<template v-if="formData.type === 'company'">
						<a-col :span="12">
							<a-form-item field="company_id" label="所属公司" :rules="[{ required: true, message: '请选择公司' }]">
								<a-select
									v-model="formData.company_id"
									placeholder="请选择公司"
									:loading="companyLoading"
									allow-clear
								>
									<a-option v-for="company in companyOptions" :key="company.id" :value="company.id">
										{{ company.name }}
									</a-option>
								</a-select>
							</a-form-item>
						</a-col>
					</template>
				</a-row>
			</a-form>
		</a-modal>

		<!-- 批量生成卡数据模态框 -->
		<a-modal v-model:visible="generateModalVisible" width="500px" :draggable="true" title="批量生成卡数据"
			@before-ok="handleGenerateSubmit" @cancel="closeGenerateModal">
			<a-form :model="generateCardFormData" ref="generateFormRef" layout="vertical">
				<a-form-item field="count" label="生成数量" :rules="[{ required: true, min: 1, max: 1000 }]">
					<a-input-number v-model="generateCardFormData.count" placeholder="请输入生成数量(1-1000)" :min="1" :max="1000" />
				</a-form-item>
				<a-form-item field="expired_days" label="过期时间(天)">
					<a-input-number v-model="generateCardFormData.expired_days" placeholder="请输入过期时间，0表示永久有效" :min="0" />
				</a-form-item>
				<a-form-item field="score" label="云豆数">
					<a-input-number v-model="generateCardFormData.score" placeholder="请输入云豆数" :min="0" />
				</a-form-item>
			</a-form>
		</a-modal>

		<!-- 卡数据列表抽屉 -->
		<a-drawer v-model:visible="cardItemDrawerVisible" width="1000px" :title="`${currentCard?.name || ''} - 卡数据列表`" placement="right">
			<a-table :data="cardItemData" :loading="cardItemLoading" :bordered="{ cell: true }" :pagination="cardItemPagination"
				@page-change="onCardItemPageChange" @page-size-change="onCardItemPageSizeChange" @sorter-change="onCardItemSorterChange">
				<template #columns>
					<a-table-column title="ID" data-index="id" :width="80" />
					<a-table-column title="卡号" data-index="card_no" :width="100" />
					<a-table-column title="卡密" data-index="beauty_card_number" :width="180" :ellipsis="true" :tooltip="true" />
					<a-table-column title="云豆数" data-index="score" :width="100" />
					<a-table-column title="已用额度" data-index="use_score" :width="120" :sortable="{sortDirections: ['descend', 'ascend']}"/>
					<a-table-column title="状态" data-index="status" :width="100" :sortable="{sortDirections: ['descend', 'ascend']}">
						<template #cell="{ record }">
							<a-tag :color="record.status === 0 ? 'green' : record.status === 1 ? 'blue' : 'red'">
								{{ record.status_text }}
							</a-tag>
						</template>
					</a-table-column>
					<a-table-column title="过期天数" data-index="expired_days" :width="120">
						<template #cell="{ record }">
							{{ record.expired_days}}天
						</template>
					</a-table-column>
					<a-table-column title="创建时间" data-index="created_at" :width="180">
						<template #cell="{ record }">
							{{ record.created_at ? new Date(record.created_at * 1000).toLocaleString('zh-CN') : '' }}
						</template>
					</a-table-column>
				</template>
			</a-table>
		</a-drawer>

		<!-- 绑定记录抽屉 -->
		<a-drawer v-model:visible="bindRecordsDrawerVisible" width="1200px" title="福利卡绑定记录" placement="right">
			<a-space fill direction="vertical">
				<a-row :gutter="16">
					<a-col :span="8">
						<a-input-search
							v-model="bindRecordsSearch"
							placeholder="搜索卡号、用户手机号或福利卡名"
							@search="onBindRecordsSearch"
							@clear="onBindRecordsSearch"
						/>
					</a-col>
				</a-row>

				<a-table :data="bindRecordsData" :loading="bindRecordsLoading" :bordered="{ cell: true }" :pagination="bindRecordsPagination"
					@page-change="onBindRecordsPageChange" @page-size-change="onBindRecordsPageSizeChange">
					<template #columns>
						<a-table-column title="ID" data-index="id" :width="80" />
						<a-table-column title="用户名" data-index="user_name" :width="120" />
						<a-table-column title="手机号" data-index="user_phone" :width="130" />
						<a-table-column title="福利卡名" data-index="card_name" :width="150" />
						<a-table-column title="卡号" data-index="card_number" :width="150" :ellipsis="true" :tooltip="true" />
						<a-table-column title="绑定时间" data-index="created_at" :width="180" />
						<a-table-column title="过期时间" data-index="expired_at" :width="180" />
						<a-table-column title="余额(云豆)" data-index="score" :width="120" />
						<a-table-column title="状态" data-index="status" :width="100">
							<template #cell="{ record }">
								<a-tag :color="record.status === 1 ? 'green' : 'red'">
									{{ record.status_text }}
								</a-tag>
							</template>
						</a-table-column>
					</template>
				</a-table>
			</a-space>
		</a-drawer>
	</div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { Message } from '@arco-design/web-vue';
import type { UploadRequest, RequestOption, FileItem } from '@arco-design/web-vue';
import useLoading from '@/hooks/loading';
import { Pagination } from '@/types/global';
import { queryCardList, submitCardForm, delCard, CardRecord, batchGenerateCardItems, queryCardBindRecords, CardBindRecord, CardBindRecordParams } from '@/api/card';
import { queryCardItemList, CardItemRecord, CardItemParams } from '@/api/cardItem';
import { uploadFile } from '@/api/upload';
import { queryAllCompanyList, CompanyRecord } from '@/api/company';

const { loading, setLoading } = useLoading(true);
const modalVisible = ref(false);
const generateModalVisible = ref(false);
const cardItemDrawerVisible = ref(false);
const bindRecordsDrawerVisible = ref(false);
const formRef = ref();
const generateFormRef = ref();
const fileList = ref<FileItem[]>([]);

// 搜索参数
const searchParams = ref({
	company_id: undefined as number | undefined,
	dateRange: [] as any[],
});

const basePagination = {
	current: 1,
	pageSize: 10,
	total: 0,
	sort: 'id',
	order: 'desc',
};

const pagination = reactive({
	...basePagination,
});

// 卡数据列表相关状态
const cardItemLoading = ref(false);
const cardItemData = ref<CardItemRecord[]>([]);
const currentCard = ref<CardRecord | null>(null);
const cardItemPagination = reactive({
	...basePagination,
});

// 绑定记录相关状态
const bindRecordsLoading = ref(false);
const bindRecordsData = ref<CardBindRecord[]>([]);
const bindRecordsSearch = ref('');
const bindRecordsPagination = reactive({
	...basePagination,
});

const generateFormData = () => {
	return {
		id: 0,
		company_id: '',
		name: '',
		image: '',
		sort_by: 0,
		score: 0,
		status: 1,
		expired_days: 0,
		type:'company',
		price: 0,
		total: 0
	};
};

const generateCardFormData = ref({
	card_id: 0,
	count: 1,
	expired_days: 0,
	score: 0,
});

const formData = ref(generateFormData());

const renderData = ref<CardRecord[]>([]);

const fetchData = async () => {
	setLoading(true);
	try {
		const params: any = {
			current: pagination.current,
			pageSize: pagination.pageSize,
		};
		
		// 添加公司搜索参数
		if (searchParams.value.company_id) {
			params.company_id = searchParams.value.company_id;
		}
		
		// 添加时间范围搜索参数
		if (searchParams.value.dateRange && searchParams.value.dateRange.length === 2) {
			params.created_at = searchParams.value.dateRange.map((date: any) => 
				date ? new Date(date).toISOString().split('T')[0] : ''
			).join(',');
		}
		
		const { data } = await queryCardList(params);
		renderData.value = data.list;
		pagination.total = data.total;
	} catch (err) {
		Message.error('获取福利卡列表失败');
	} finally {
		setLoading(false);
	}
};

const onPageChange = (current: number) => {
	pagination.current = current;
	fetchData();
};

const onPageSizeChange = (pageSize: number) => {
	pagination.pageSize = pageSize;
	pagination.current = 1;
	fetchData();
};

const companyOptions = ref<CompanyRecord[]>([]);
const companyLoading = ref(false);
const fetchCompanyOptions = async () => {
	companyLoading.value = true;
	try {
		const { data } = await queryAllCompanyList();
		companyOptions.value = data;
	} catch (err) {
		Message.error('获取公司列表失败');
	} finally {
		companyLoading.value = false;
	}
};

const openModal = (record?: CardRecord) => {
	if (record) {
		formData.value = {
			id: record.id,
			company_id: record.company_id,
			name: record.name,
			image: record.image,
			sort_by: record.sort_by,
			score: record.score,
			status: 1,
			expired_days: record.expired_days,
		};

		fileList.value = [{ uid: '1', url: record.image_url } as FileItem];
	} else {
		formData.value = generateFormData();
		fileList.value = [];
	}
	modalVisible.value = true;
};

const closeModal = () => {
	modalVisible.value = false;
	formData.value = generateFormData();
};

const handleUpload = (option: any): UploadRequest => {
	try {
		const { onProgress, onError, onSuccess, fileItem } = option;

		const uploadFormData = new FormData();
		uploadFormData.append('file', fileItem.file);
		
		uploadFile(uploadFormData).then(({ data }) => {
			formData.value.image = data.url;
			fileList.value = [{ url: data.url } as FileItem];

			Message.success('上传成功');
		}).catch((err) => {
			Message.error('上传失败');
		});

		return {
			abort: () => { },
		};
	} catch (err) {
		Message.error('上传失败');
		return {
			abort: () => { },
		};
	}
};

const beforeRemove = async (fileItem: FileItem): Promise<boolean> => {
	formData.value.image = '';
	fileList.value = [];
	return true;
};

const handleSubmit = async (done: (closed: boolean) => void) => {
	setLoading(true);
	try {
		const submitData = {
			...formData.value,
			status: formData.value.status || 1
		};
		const res = await submitCardForm(submitData);
		Message.success('操作成功');
		closeModal();
		fetchData();
		done(true);
	} catch (err) {
		done(false);
	} finally {
		setLoading(false);
	}
};

const handleDelete = async (id: number) => {
	try {
		await delCard(id);
		Message.success('删除成功');
		fetchData();
	} catch (err) {
		Message.error('删除失败');
	}
};

const onSearch = () => {
	pagination.current = 1;
	fetchData();
};

const resetSearch = () => {
	searchParams.value = {
		company_id: undefined,
		dateRange: [],
	};
};

const openGenerateModal = (record: CardRecord) => {
	generateCardFormData.value = {
		card_id: record.id,
		count: 1,
		expired_days: record.expired_days,
		score: record.score,
	};
	generateModalVisible.value = true;
};

const closeGenerateModal = () => {
	generateModalVisible.value = false;
	generateCardFormData.value = {
		card_id: 0,
		count: 1,
		expired_days: 0,
		score: 0,
	};
};

const handleGenerateSubmit = async (done: (closed: boolean) => void) => {
	setLoading(true);
	try {
		await batchGenerateCardItems(generateCardFormData.value).then((res: any) => {
			Message.success(`成功生成 卡数据`);
			closeGenerateModal();

			fetchData();
			done(true);
		}).catch((err) => {
			Message.error('生成失败');
		});
	} catch (err) {
		done(false);
	} finally {
		done(false);
		setLoading(false);
	}
};

// 卡数据列表相关方法
const openCardItemList = async (record: CardRecord) => {
	currentCard.value = record;
	cardItemDrawerVisible.value = true;
	cardItemPagination.current = 1;
	cardItemPagination.sort = 'id';
	cardItemPagination.order = 'desc';
	await fetchCardItemData();
};

const fetchCardItemData = async () => {
	if (!currentCard.value) return;
	
	cardItemLoading.value = true;
	try {
		const params: CardItemParams = {
			card_id: currentCard.value.id,
			page: cardItemPagination.current,
			limit: cardItemPagination.pageSize,
			sort: cardItemPagination.sort,
			order: cardItemPagination.order,
		};
		
		const { data } = await queryCardItemList(params);
		cardItemData.value = data.list;
		cardItemPagination.total = data.total;
	} catch (err) {
		Message.error('获取卡数据列表失败');
	} finally {
		cardItemLoading.value = false;
	}
};

const onCardItemPageChange = (current: number) => {
	cardItemPagination.current = current;
	fetchCardItemData();
};

const onCardItemPageSizeChange = (pageSize: number) => {
	cardItemPagination.pageSize = pageSize;
	cardItemPagination.current = 1;
	fetchCardItemData();
};

const onCardItemSorterChange = (dataIndex: any,direction: any) => {
	cardItemPagination.current = 1;
	cardItemPagination.pageSize = 10;
	cardItemPagination.sort = dataIndex;
	cardItemPagination.order = direction === 'ascend' ? 'asc' : 'desc';
	fetchCardItemData();
};

// 绑定记录相关方法
const openBindRecordsDrawer = async () => {
	bindRecordsDrawerVisible.value = true;
	bindRecordsPagination.current = 1;
	bindRecordsSearch.value = '';
	await fetchBindRecordsData();
};

const fetchBindRecordsData = async () => {
	bindRecordsLoading.value = true;
	try {
		const params: CardBindRecordParams = {
			current: bindRecordsPagination.current,
			pageSize: bindRecordsPagination.pageSize,
			search: bindRecordsSearch.value,
		};
		
		const { data } = await queryCardBindRecords(params);
		bindRecordsData.value = data.list;
		bindRecordsPagination.total = data.total;
	} catch (err) {
		Message.error('获取绑定记录失败');
	} finally {
		bindRecordsLoading.value = false;
	}
};

const onBindRecordsPageChange = (current: number) => {
	bindRecordsPagination.current = current;
	fetchBindRecordsData();
};

const onBindRecordsPageSizeChange = (pageSize: number) => {
	bindRecordsPagination.pageSize = pageSize;
	bindRecordsPagination.current = 1;
	fetchBindRecordsData();
};

const onBindRecordsSearch = () => {
	bindRecordsPagination.current = 1;
	fetchBindRecordsData();
};

onMounted(() => {
	fetchCompanyOptions();
	fetchData();
});
</script>

<style scoped lang="less">
.container {
	padding: 0 20px 20px 20px;
}
</style>

<script lang="ts">
export default {
	name: 'CardList',
};
</script> 